package com.maotouying.owlsmart.LoginPage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.maotouying.owlsmart.MainPage.FragmentManagerActivity;
import com.maotouying.owlsmart.R;
import com.maotouying.owlsmart.SmartUtil.Http.portPath;
import com.maotouying.owlsmart.SmartUtil.SystemUtil;
import com.maotouying.owlsmart.SmartUtil.md5.md5Encrypt;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
//忘记密码
public class ForgetActivity extends AppCompatActivity {

    private EditText edt_phone,edt_email;
    private Button bt_checkout,bt_finish;

    private EditText edt_newpassword,edt_password;

    private String smartPath;

    private String checkout = "/owl/user/check_email_phone.do";
    private String alter = "/owl/user/reset_password.do";


    private String username,email,phone,passwordNew;

    private LinearLayout ll_alter,ll_checkout;

    private ImageView iv_back;
    private md5Encrypt md5;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget);
        SystemUtil.setStatusBarColor(this, this.getResources().getColor(R.color.top_background_color));


        //拿到Address根地址
        portPath port = new portPath();
        smartPath = port.getPath(ForgetActivity.this);

        initView();

    }

    private void initView(){


        ll_alter= (LinearLayout) findViewById(R.id.ll_alter);
        ll_checkout= (LinearLayout) findViewById(R.id.ll_checkout);


        edt_email = (EditText)findViewById(R.id.edt_email);
        edt_phone = (EditText)findViewById(R.id.edt_phone);
        bt_checkout = (Button) findViewById(R.id.bt_checkout);


        edt_password= (EditText)findViewById(R.id.edt_password);
        edt_newpassword= (EditText)findViewById(R.id.edt_newpassword);
        bt_finish= (Button) findViewById(R.id.bt_finish);



        edt_email.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        edt_email.setSingleLine();
        edt_phone.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        edt_phone.setSingleLine();
        edt_password.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        edt_password.setSingleLine();
        edt_newpassword.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        edt_newpassword.setSingleLine();

        iv_back= (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        bt_checkout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (edt_email.getText().toString().isEmpty()|edt_phone.getText().toString().isEmpty()){

                    Toast.makeText(ForgetActivity.this, "邮箱/手机号输入为空", Toast.LENGTH_LONG).show();
                }else {
                    postTest();
                }
            }
        });

        bt_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               if(edt_password.getText().toString().equals(edt_newpassword.getText().toString())) {

                   passwordNew = edt_password.getText().toString();
                   postalter();
               }else {
                   Toast.makeText(ForgetActivity.this, "两次输入的密码不统一", Toast.LENGTH_LONG).show();
               }



            }
        });

    }






    public void postTest(){
        OkHttpClient client = new OkHttpClient();
        //post请求
        FormBody formBody = new FormBody.Builder()
                .add("email",edt_email.getText().toString())
                .add("phone",edt_phone.getText().toString())
                .build();

        Request request = new Request.Builder().url(smartPath+checkout)
                .post(formBody).build();

        client.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }

            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String result = response.body().string();
                    System.out.println("result：："+result);
                    Message msg = new Message();
                    msg.what = 16;
                    Bundle bundle = new Bundle();
                    bundle.putString("result", result);//往Bundle中存放数据
                    msg.setData(bundle);
                    Thandler.sendMessage(msg);
                }
            }
        });
    }



    private Handler Thandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 16:
                    String result = msg.getData().getString("result");//接受msg传递过来的参数
                   // System.out.println("Handler::::"+result);
                    //这里操作更新ui
                    JSONObject code = JSONObject.parseObject(result);
                    int status = code.getInteger("status");
                    if(status==0){
                        //换个页面
                        username = code.getString("data");//用户名
                        email = edt_email.getText().toString();
                        phone = edt_phone.getText().toString();

                        //隐藏邮箱密码布局
                        ll_checkout.setVisibility(View.GONE);
                        ll_alter.setVisibility(View.VISIBLE);
                    }else {

                       String returnMsg = code.getString("msg");
                       Toast.makeText(ForgetActivity.this, returnMsg, Toast.LENGTH_LONG).show();
                    }



                    break;
                case 22:
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            /**
                             *要执行的操作
                             */

                           finish();

                        }
                    };
                    Timer timer = new Timer();
                    timer.schedule(task, 2000);//3秒后执行TimeTask的run方法

                    break;
                case 23:
                    Toast.makeText(ForgetActivity.this, "网络请求失败", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };



    public void postalter(){

        md5 = new md5Encrypt();
        OkHttpClient client = new OkHttpClient();
        //post请求
        FormBody formBody = new FormBody.Builder()
                .add("email",email)
                .add("phone",phone)
                .add("passwordNew",md5.toMd5(passwordNew))
                .add("username",username)
                .build();

        Request request = new Request.Builder().url(smartPath+alter).post(formBody).build();

        client.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }

            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String result = response.body().string();
                   // System.out.println(result);
                    JSONObject code = JSONObject.parseObject(result);
                    int status = code.getInteger("status");
                    if(status==0){

                        Toast.makeText(ForgetActivity.this, "修改成功，请重新登录", Toast.LENGTH_LONG).show();
                        Message msg = new Message();
                        msg.what = 22;
                        Thandler.sendMessage(msg);
                    }else {
                        Message msg = new Message();
                        msg.what = 23;
                        Thandler.sendMessage(msg);
                          }

                }
            }
        });
    }


}